/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.config;

import org.elsfs.cloud.common.security.filter.phone.sms.PhoneSmsAuthenticationFilter;
import org.elsfs.cloud.common.security.filter.phone.sms.PhoneSmsAuthenticationProvider;
import org.elsfs.cloud.common.security.filter.phone.sms.send.MemorySmsCodeService;
import org.elsfs.cloud.common.security.filter.phone.sms.send.SmsCodeService;
import org.elsfs.cloud.common.security.filter.phone.sms.send.SmsSendFilter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 配置手机号短信登录
 *
 * @author zeng
 */
public final class PhoneSmsAuthenticationSecurityConfigurer
    extends AbstractSecurityFilterConfigurer<
        PhoneSmsAuthenticationSecurityConfigurer, PhoneSmsAuthenticationFilter> {

  public PhoneSmsAuthenticationSecurityConfigurer() {
    super(new PhoneSmsAuthenticationFilter());
  }

  @Override
  public void init(HttpSecurity http) throws Exception {
    PhoneSmsAuthenticationProvider provider =
        new PhoneSmsAuthenticationProvider(
            getPasswordEncoder(http), getElsfsUserDetailsService(http), getSmsCodeService(http));
    provider.setMessageSource(getMessageSource());
    http.authenticationProvider(provider);
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    SmsSendFilter smsSendFilter = new SmsSendFilter();
    smsSendFilter.setSmsCodeService(getSmsCodeService(http));
    http.addFilterAfter(smsSendFilter, UsernamePasswordAuthenticationFilter.class);
  }

  protected SmsCodeService getSmsCodeService(HttpSecurity http) {
    SmsCodeService smsCodeService = http.getSharedObject(SmsCodeService.class);
    try {
      if (smsCodeService == null) {
        ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
        smsCodeService = applicationContext.getBean(SmsCodeService.class);
      }
    } catch (BeansException e) {
      smsCodeService = new MemorySmsCodeService();
    }
    http.setSharedObject(SmsCodeService.class, smsCodeService);
    return smsCodeService;
  }
}
